//
//  ATMainDetailViewController.m
//  Adorable_Things
//
//  Created by huzhiyan on 16/1/13.
//  Copyright © 2016年 Banana Inc. All rights reserved.
//

#import "ATMainDetailViewController.h"
#import "ATDetailViewController.h"
#import "ATDetailModel.h"
#import "ATDetailHeaderCustomView.h"
#import "ATCommentViewController.h"
#import "ATLoginViewController.h"

@interface ATMainDetailViewController () <UIScrollViewDelegate,UIGestureRecognizerDelegate>

@property (nonatomic, strong) ATDetailViewController *detailVC;
@property (nonatomic, strong) ATCommentViewController *commentVC;
@property (nonatomic, strong) ATDetailModel *model;
@property (nonatomic, strong) UIWebView *webView;
@property (nonatomic, strong) ATDetailHeaderCustomView *headerCustomView;
@property (nonatomic, assign) NSInteger isLike;


@end

@implementation ATMainDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    // Do any additional setup after loading the view from its nib.
    // 取消自动布局
    self.edgesForExtendedLayout = UIRectEdgeNone;
    _isLike = [_secondModel.favorite integerValue];
    [self setSubScrollView];
    [self addSubHeaderView];
    [self addChildVC];
    [self setUpData];
}

#pragma mark --- 请求数据
// 请求数据
- (void)setUpData
{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"item_id"] = _item_id;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:@"http://api.menghuoapp.com/v1/item/detail" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dataDic = responseObject[@"data"];
        _model = [[ATDetailModel alloc] init];
        [_model setValuesForKeysWithDictionary:dataDic];
        _detailVC.model = _model;
        _commentVC.post_ID = _model.item_id;
        _commentVC.topic_ID = _model.tb_item_type;
        [_detailVC.tableView reloadData];
        [self setSubWebViewcontent];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

#pragma mark --- 添加导航自定义视图
// 添加导航自定义视图
- (void)addSubHeaderView
{
    _headerCustomView = [[[UINib nibWithNibName:@"ATDetailHeaderCustomView" bundle:nil] instantiateWithOwner:self options:nil] lastObject];
    _headerCustomView.frame = CGRectMake(0, 20, kWidth, 45);
    UIImage *likeImage = nil;
    if ([_secondModel.favorite integerValue]) {
        likeImage = [UIImage imageNamed:@"iconfont-xihuan-2"];
    } else {
        likeImage = [UIImage imageNamed:@"iconfont-tubiao"];
    }
    UIImage *likeImageView = [[UIImage imageWithImage:likeImage scaleToSize:CGSizeMake(25, 25)] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    [_headerCustomView.likeItemButton setImage:likeImageView forState:(UIControlStateNormal)];
    [self.view addSubview:_headerCustomView];
    
    [_headerCustomView.backItemButton addTarget:self action:@selector(backItemButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    [_headerCustomView.likeItemButton addTarget:self action:@selector(likeItemButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    _headerCustomView.likeItemButton.adjustsImageWhenHighlighted = NO;
    [_headerCustomView.firstButton addTarget:self action:@selector(headerCustomViewButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    _headerCustomView.firstButton.adjustsImageWhenHighlighted = NO;
    [_headerCustomView.secondButton addTarget:self action:@selector(headerCustomViewButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    [_headerCustomView.thirdButton addTarget:self action:@selector(headerCustomViewButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    [_headerCustomView.likeItemButton addTarget:self action:@selector(likeItemButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
}

- (void)backItemButtonClick:(UIButton *)button
{
    if ([_delegte respondsToSelector:@selector(refreshViewController)]) {
        [_delegte refreshViewController];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark --- 跳转登陆界面
- (void)likeItemButtonClick:(UIButton *)button
{
    if ([ATUserManager shareManager].isLogin) {
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        dic[@"auth_token"] = [ATUserManager shareManager].auth_token;
        dic[@"item_id"] = _item_id;
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        _isLike = !_isLike;
        if (_isLike) {
            [manager POST:@"http://api.menghuoapp.com/v1/item/mark" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                [self setUpData];
                [_headerCustomView.likeItemButton setImage:[UIImage imageNamed:@"iconfont-xihuan-2"] forState:(UIControlStateNormal)];
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            }];
        } else {
            [manager POST:@"http://api.menghuoapp.com/v1/item/unmark" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                [self setUpData];
                [_headerCustomView.likeItemButton setImage:[UIImage imageNamed:@"iconfont-tubiao"] forState:(UIControlStateNormal)];
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            }];
        }

    } else {
    ATLoginViewController *loginVC = [[ATLoginViewController alloc] init];
    UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:loginVC];
    loginVC.navigationController.navigationBar.hidden = YES;
    [self presentViewController:naVC animated:YES completion:nil];
        
    }
}

#pragma mark --- 添加子控制器
// 添加子控制器
- (void)addChildVC
{
    _detailVC = [[ATDetailViewController alloc] init];
    _detailVC.item_id = _item_id;
    _detailVC.view.frame = CGRectMake(0, 0, kWidth, kHeight);
    [self addChildViewController:_detailVC];
    [self.scrollView addSubview:_detailVC.view];

    _commentVC = [[ATCommentViewController alloc] init];
    [self addChildViewController:_commentVC];
    _commentVC.view.frame = CGRectMake(kWidth * 2, 0, kWidth, kHeight);
    [self.scrollView addSubview:_commentVC.view];
    
}

#pragma mark --- 添加webView视图
// 设置webView
- (void)setSubWebViewcontent
{
    _webView = [[UIWebView alloc] initWithFrame:CGRectMake(kWidth, 0, kWidth, kHeight - 65)];
    _webView.backgroundColor = [UIColor whiteColor];
    _webView.scalesPageToFit = YES;
    _model.descrip = [NSString stringWithFormat:@"<head><style>img{width:%fpx !important;}</style></head>%@",kWidth ,_model.descrip];
    [_webView loadHTMLString:_model.descrip baseURL:nil];
    [self.scrollView addSubview:_webView];
}

#pragma mark --- 添加scrollView视图
// 设置scrollView
- (void)setSubScrollView
{
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 65, kWidth, kHeight - 65)];
    _scrollView.contentSize = CGSizeMake(kWidth * 3, kHeight - 65);
    _scrollView.pagingEnabled = YES;
    _scrollView.bounces = NO;
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.showsVerticalScrollIndicator = NO;
    _scrollView.delegate = self;
    [self.view addSubview:_scrollView];
}

#pragma mark --- 实现scrollView代理方法
// 实现scrollView代理方法
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.x == 0) {
        [self changeSlideLineViewlocation:_headerCustomView.firstButton.left];
    }
    if (scrollView.contentOffset.x == kWidth) {
        [self changeSlideLineViewlocation:_headerCustomView.secondButton.left];
    }
    if (scrollView.contentOffset.x == kWidth * 2) {
        [self changeSlideLineViewlocation:_headerCustomView.thirdButton.left];
    }
}

#pragma mark --- 导航自定义view Button点击方法实现
// 导航自定义view Button点击方法实现
- (void)headerCustomViewButtonClick:(UIButton *)button
{
    if ([button isEqual:_headerCustomView.firstButton]) {
        [self changeSlideLineViewlocation:_headerCustomView.firstButton.left];
        [_scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
    }
    if ([button isEqual:_headerCustomView.secondButton]) {
        [self changeSlideLineViewlocation:_headerCustomView.secondButton.left];
        [_scrollView setContentOffset:CGPointMake(kWidth, 0) animated:YES];
    }
    if ([button isEqual:_headerCustomView.thirdButton]) {
        [self changeSlideLineViewlocation:_headerCustomView.thirdButton.left];
        [_scrollView setContentOffset:CGPointMake(kWidth * 2, 0) animated:YES];
    }
}

#pragma mark --- 导航自定义滑动view动画方法实现
// 改变位置动画
- (void)changeSlideLineViewlocation:(CGFloat)width
{
    [UIView animateWithDuration:0.2 animations:^{
        _headerCustomView.slideLineView.frame = CGRectMake(width, _headerCustomView.slideLineView.top, _headerCustomView.slideLineView.width, _headerCustomView.slideLineView.height);
    }];

}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
